package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServicelmpl implements ReportService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverReport(LocalDate begin, LocalDate end) {
        //组装x轴数据集合
        List<LocalDate> dateArrayList = new ArrayList<>();
        dateArrayList.add(begin);
        //累加每天日期，创建日期X轴集合
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);//累加日期
            dateArrayList.add(begin);
        }
        //创建y轴集合
        List<Double> turnoverList = new ArrayList<>();
        //遍历x轴数据，组装y轴数据集合
        for (LocalDate localDate : dateArrayList) {
            //开始时间
            LocalDateTime minTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //结束时间
            LocalDateTime maxTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //封装map集合
            HashMap<Object, Object> map = new HashMap<>();
            map.put("status", Orders.COMPLETED);//获取已完成订单的营业额
            map.put("begin", minTime);
            map.put("end", maxTime);
            //获取营业总额
            Double turnover = orderMapper.sum(map);
            //当营业额为null时，赋值0.0
            if (turnover == null) {
                turnover = 0.00;
            }
            //组装y轴集合
            turnoverList.add(turnover);
            log.info("营业额：{}", turnoverList);
        }
        //将x、y轴数据按照接口文档格式要求，封装成一个VO对象返回
        TurnoverReportVO reportVo = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateArrayList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return reportVo;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userReport(LocalDate begin, LocalDate end) {
        log.info("用户统计：{}", begin, end);
        //组装x轴日期数据集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //累加每天日期，创建日期X轴集合
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建y轴总用户数集合
        List<Integer> totalUserList = new ArrayList<>();
        //创建y轴新增用户集合
        List<Integer> newUserList = new ArrayList<>();
        //遍历x轴数据，组装y轴数据集合
        for (LocalDate localDate : dateList) {
            //开始时间
            LocalDateTime minTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //结束时间
            LocalDateTime maxTime = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("end", maxTime);
            //总用户数量
            Integer totalUser = userMapper.getcount(map);
            map.put("begin", minTime);
            //新增用户数
            Integer newUser = userMapper.getcount(map);
            //将上面的数据加入集合中，组成y轴数据
            totalUserList.add(totalUser);
            newUserList.add(newUser);
            //将数据封装到VO中返回,以字符串的形式，并且用，连接
        }
        UserReportVO userreport = UserReportVO.builder().totalUserList(StringUtils.join(totalUserList, ",")).//总用户数量
                newUserList(StringUtils.join(newUserList, ",")).//每日用户新增数量
                dateList(StringUtils.join(dateList, ",")).//日期合集
                build();
        return userreport;

    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersReport(LocalDate begin, LocalDate end) {
        log.info("订单统计：{}",begin,end);
        //组装x轴日期数据集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //累加每天日期，创建日期X轴集合
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建y轴每日订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //创建y轴每日有效订单数
        List<Integer> vailOrderCountList = new ArrayList<>();
        //循环遍历日期集合，查询每日订单总数和有效订单数
        for (LocalDate localDate : dateList) {
            LocalDateTime begintime = LocalDateTime.of(localDate, LocalTime.MIN);//开始时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);//结束时间
            //创建map集合，封装上查询到的数据
            HashMap<Object, Object> map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("end", endTime);
            map.put("begin", begintime);
            //每日订单总数
            Integer orderCount = orderMapper.getcountBy(map);
            //每日有效订单数
            Integer vailOrderCount = orderMapper.getcountBy(map);
            //将上面的数据加入集合中，组成y轴数据
            orderCountList.add(orderCount);
            vailOrderCountList.add(vailOrderCount);
        }
        //计算时间区内的订单总数 累加总数stream().reduce
        Integer totalOrder = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区内的有效订单总数
        Integer vaildOrderCount = vailOrderCountList.stream().reduce(Integer::sum).get();
        //获取订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrder != 0) {
            orderCompletionRate = vaildOrderCount.doubleValue() / totalOrder;
        }
        log.info("订单完成率：{}",orderCompletionRate);
        //将数据封装到VO中返回,以字符串的形式，并且用，连接
        OrderReportVO build = OrderReportVO.builder().orderCountList(StringUtils.join(orderCountList, ",")).
                totalOrderCount(totalOrder).
                validOrderCount(vaildOrderCount).
                orderCompletionRate(orderCompletionRate).
                dateList(StringUtils.join(dateList, ",")).
                validOrderCountList(StringUtils.join(vailOrderCountList, ","))
                .build();
        return build;
    }

    /**
     * 销量排名
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO SalesTop10Report(LocalDate begin, LocalDate end) {
        log.info("销量排名:{}",begin,end);
        //获取开始时间
        LocalDateTime begintimes = LocalDateTime.of(begin, LocalTime.MIN);
        //获取结束时间
        LocalDateTime endtimes = LocalDateTime.of(end, LocalTime.MAX);
        //获取销量排名方法
        List<GoodsSalesDTO> SalesDTOS=orderMapper.top10Report(begintimes,endtimes);
        //将GoodsSalesDTO里面的name以VO里面的nameList的list集合循环查询出来
        List<String> names = SalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //将对象以字符串类型并且用，隔开
        String nameList = StringUtils.join(names, ",");
        //将GoodsSalesDTO里面的number以VO里面的numberList的list集合循环查询出来
        List<Integer> numbers = SalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //将对象以字符串类型并且用，隔开
        String numberList = StringUtils.join(numbers, ",");
        //将数据封装到VO中返回,
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder().numberList(numberList).nameList(nameList).build();
        return salesTop10ReportVO;
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessDate(HttpServletResponse response) {
        //查询近30天的订单运营数据报表,获取30-1的时间
        LocalDate begindate = LocalDate.now().minusDays(30);
        LocalDate enddate = LocalDate.now().minusDays(1);
        //需要将上面的时间转化为localDateTime格式，
        LocalDateTime begin = LocalDateTime.of(begindate, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(enddate, LocalTime.MAX);
        //获取概览数据
        BusinessDataVO businessDataVO = workspaceService.lookbusinessData(begin,end);
        //通过poi将数据写到excel表格中
        InputStream resource = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //获取新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(resource);
            //获取sheet页，
            XSSFSheet sheet = excel.getSheet("sheet1");
            //填充第一行表格数据，时间
            sheet.getRow(1).getCell(1).setCellValue("时间"+begindate+"至"+enddate);
            //填充概览数据第4行的营业额表格数据
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            //填充概览数据第4行的订单完成率表格数据
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //填充概览数据第4行的订单新增用户表格数据
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            //填充概览数据第5行的订单有效表格数据
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //填充概览数据第5行的平均客单价表格数据
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //循环遍历30天日期，填充数据报表
            for (int i = 0; i < 30; i++) {
                LocalDate localDate = begindate.plusDays(i);
                //需要将上面的时间转化为localDateTime格式，
                LocalDateTime datebegin = LocalDateTime.of(localDate, LocalTime.MIN);
                LocalDateTime dateend = LocalDateTime.of(localDate, LocalTime.MAX);
                //获取概览数据
                BusinessDataVO businessDataVO1 = workspaceService.lookbusinessData(datebegin, dateend);
                //获取第行，填充数据
                XSSFRow row = sheet.getRow(7 + i);
                //获取日期，填充表格数据
                row.getCell(1).setCellValue(localDate.toString());
                //获取营业额,有效订单，订单完成率，平均客单价，新增用户数，填充数据
                row.getCell(2).setCellValue(businessDataVO1.getTurnover());
                row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO1.getNewUsers());

            }
            //通过输出流将excel表格放入客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            excel.close();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }






    }
}